package com.ruoyi.web.controller.system;
import com.ruoyi.framework.manager.factory.AsyncFactory;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.system.domain.AllCustomsCodes;
import com.ruoyi.system.service.IAllCustomsCodesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 全部海关编码Controller
 * 
 * @author ruoyi
 * @date 2025-02-07
 */
@RestController
@RequestMapping("/system/codesAll")
public class AllCustomsCodesControllerAll extends BaseController
{
    @Autowired
    private IAllCustomsCodesService allCustomsCodesService;
    // 配置文件中存储文件路径
    @Value("${kuaiqiao.profile}")
    private String uploadDir;

    /**
     * 下载服务器上的文件
     *
     * @param type 要下载的文件类型
     * @return 下载的文件
     */
    @PostMapping("/downloadFile")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam("type") String type) throws IOException {
//        @RequestParam String fileName
        String fileName = null;
        if (type!=null && type.equals("0")) {
            fileName = "quanbu.xlsx";
        }else if (type!=null && type.equals("1")){
            fileName = "teshu.xlsx";
        }else{
            fileName = "jianyi.xlsx";
        }

        // 构建文件路径
        String filePath = uploadDir + "/" + fileName;

        // 读取文件
        InputStream inputStream = new FileInputStream(filePath);

        // 获取文件的 MIME 类型（这里假设文件是 XLSX 格式）
        String mimeType = Files.probeContentType(Paths.get(filePath));
        if (mimeType == null) {
            mimeType = "application/octet-stream";  // 默认二进制流类型
        }

        // 创建输入流资源
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        headers.add(HttpHeaders.CONTENT_TYPE, mimeType);
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(Files.size(Paths.get(filePath))));

        // 返回文件流响应
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
    /**
     * 查询全部海关编码列表
     */
    @PreAuthorize("@ss.hasPermi('source:customs:list')")
    @GetMapping("/list")
    public TableDataInfo list(AllCustomsCodes allCustomsCodes)
    {
        startPage();
        List<AllCustomsCodes> list = allCustomsCodesService.selectAllCustomsCodesList(allCustomsCodes);
        return getDataTable(list);
    }

    /**
     * 导出全部海关编码列表
     */
    @PreAuthorize("@ss.hasPermi('source:customs:export')")
    @Log(title = "全部海关编码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AllCustomsCodes allCustomsCodes)
    {
        List<AllCustomsCodes> list = allCustomsCodesService.selectAllCustomsCodesList(allCustomsCodes);
        ExcelUtil<AllCustomsCodes> util = new ExcelUtil<AllCustomsCodes>(AllCustomsCodes.class);
        util.exportExcel(response, list, "全部海关编码数据");
    }

    /**
     * 获取全部海关编码详细信息
     */
    @PreAuthorize("@ss.hasPermi('source:customs:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(allCustomsCodesService.selectAllCustomsCodesById(id));
    }

    /**
     * 新增全部海关编码
     */
    @PreAuthorize("@ss.hasPermi('source:customs:add')")
    @Log(title = "全部海关编码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AllCustomsCodes allCustomsCodes)
    {
        return toAjax(allCustomsCodesService.insertAllCustomsCodes(allCustomsCodes));
    }

    /**
     * 修改全部海关编码
     */
    @PreAuthorize("@ss.hasPermi('source:customs:edit')")
    @Log(title = "全部海关编码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AllCustomsCodes allCustomsCodes)
    {
        return toAjax(allCustomsCodesService.updateAllCustomsCodes(allCustomsCodes));
    }

    /**
     * 删除全部海关编码
     */
    @PreAuthorize("@ss.hasPermi('source:customs:remove')")
    @Log(title = "全部海关编码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(allCustomsCodesService.deleteAllCustomsCodesByIds(ids));
    }

    /**
     * 新增数据匹配
     */
    @PreAuthorize("@ss.hasPermi('source:customs:import')")
    @Log(title = "数据匹配", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public JSONObject uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("type") String type) {
        JSONObject res = new JSONObject();
        if (file.isEmpty()) {
            res.put("error", "文件不能为空");
            return res;
        }
        try {
            InputStream inputStream = file.getInputStream();
            AsyncManager.me().execute(AsyncFactory.importExcelDataSj(inputStream,type));
            res.put("success","数据持续导入中，请稍后刷新查看～");
            res.put("code","200");
//            allCustomsCodesService.importExcelData(inputStream,type);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            res.put("error", e.getMessage());
            return res;
        }
    }

}
